import fs from 'fs-extra';
import iconv from 'iconv-lite';
import { Nullable } from '../typings/index.js';
import { toolchain } from '../toolchain.js';
import path from 'path';
import normalizePath from 'normalize-path';

export function strArrayToMap(arr: string[]): { [key: string]: true } {
    const out: { [key: string]: true } = {};
    for (const e of arr) {
        out[e] = true;
    }
    return out;
}

export async function readGB2312(file: string): Promise<string> {
    const content = await fs.readFile(file);
    return iconv.decode(content, 'gbk');
}

export async function writeGB2312(file: string, content: string): Promise<void> {
    const buff = iconv.encode(content, 'gbk');
    await fs.writeFile(file, buff);
}

export function eitherExists(...choices: string[]): Nullable<string> {
    for (const c of choices) {
        if (fs.existsSync(c)) return c;
    }
    return null;
}

export function standardPath(p: string): string {
    if (path.isAbsolute(p)) {
        p = path.relative(toolchain.opts.projectRoot, p);
    }
    return normalizePath(p);
}
